package com.firstProject.Dao.Impl;

import com.firstProject.Dao.DeviceRealDataDao;
import com.firstProject.model.Device;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.stereotype.Repository;

import javax.sql.DataSource;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.List;

@Repository
public class DeviceRealDataDaoImpl implements DeviceRealDataDao{

    private JdbcTemplate template;
    DateFormat dateFormater = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

    @Autowired
    @Qualifier("dataSource")
    public void setTemplate(DataSource dataSource){
        this.template = new JdbcTemplate(dataSource);
    }

    public List<Device> deviceRealData(){
        String sql = "SELECT * ,device.id did from realdata RIGHT OUTER JOIN device on realdata.deviceId=device.id";
        return this.template.query(sql, new RowMapper<Device>() {
            @Override
            public Device mapRow(ResultSet rs,int i) throws SQLException {
                Device device = new Device();
                device.setId(rs.getString("did"));
                device.setTvalue(rs.getString("tvalue"));
                if(rs.getDouble("latitude")!=0){
                    device.setLatitude(rs.getDouble("latitude"));
                    device.setLongitude(rs.getDouble("longitude"));
                }
                device.setDeviceName(rs.getString("deviceName"));
                String datetime = rs.getString("update_at");
                try {
                    String date = dateFormater.format(dateFormater.parse(datetime));
                    device.setDate(date);
                }catch (Exception e){
                    System.out.println(e);
                }
                return device;
            }
        });
    }
}
